package com.eastedu.report.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eastedu.common.enums.Section;
import com.eastedu.exception.ServiceException;
import com.eastedu.report.common.model.parameter.ReportExportParameter;
import com.eastedu.report.common.model.parameter.ReportGenerateParameter;
import com.eastedu.report.common.model.po.HistoryReportFromUpgradePO;
import com.eastedu.report.common.model.po.ReportExportTaskPO;
import com.eastedu.report.mapper.HistoryReportFromUpgradeMapper;
import com.eastedu.report.mapper.ReportExportTaskMapper;
import com.eastedu.report.service.ReportExportTaskService;
import com.eastedu.template.model.DocFileData;
import com.eastedu.template.model.ReportResult;
import com.eastedu.template.model.SchoolReportFileData;
import com.eastedu.utils.PrimaryKeyGenerator;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * The type Report export task service.
 *
 * @author superman
 */
@Service
public class ReportExportTaskServiceImpl implements ReportExportTaskService {
    private final ReportExportTaskMapper reportExportTaskMapper;
    private final HistoryReportFromUpgradeMapper historyReportFromUpgradeMapper;

    /**
     * Instantiates a new Report export task service.
     *
     * @param reportExportTaskMapper         the report export task mapper
     * @param historyReportFromUpgradeMapper the history report from upgrade mapper
     */
    public ReportExportTaskServiceImpl(ReportExportTaskMapper reportExportTaskMapper,
                                       HistoryReportFromUpgradeMapper historyReportFromUpgradeMapper) {
        this.reportExportTaskMapper = reportExportTaskMapper;
        this.historyReportFromUpgradeMapper = historyReportFromUpgradeMapper;
    }

    @Override
    public ReportResult create(ReportGenerateParameter generateParameter) {
        if (generateParameter.isDebug()) {
            return ReportResult.builder()
                    .taskId("debug")
                    .state(1)
                    .url("调试模式")
                    .build();
        }
        ReportExportTaskPO po = reportExportTaskMapper.selectOne(Wrappers.<ReportExportTaskPO>lambdaQuery()
                                                                         .eq(ReportExportTaskPO::getSchoolGroupId, generateParameter.getSchoolGroupId())
                                                                         .eq(ReportExportTaskPO::getSchoolGuid, generateParameter.getSchoolGuid())
                                                                         .eq(ReportExportTaskPO::getSectionCode, generateParameter.getSection())
                                                                         .eq(ReportExportTaskPO::getCodeType, generateParameter.getCodeType())
                                                                         .eq(ReportExportTaskPO::getDateCode, generateParameter.getDateCode())
        );
        return Optional.ofNullable(po)
                .map(task -> {
                    reportExportTaskMapper.update(null, Wrappers.<ReportExportTaskPO>lambdaUpdate()
                            .set(ReportExportTaskPO::getState, 1)
                            .set(ReportExportTaskPO::getContent, "处理中")
                            .eq(ReportExportTaskPO::getId, task.getId())
                    );
                    return ReportResult.builder()
                            .taskId(task.getTaskId())
                            .state(1)
                            .url("处理中")
                            .build();
                })
                .orElseGet(() -> {
                    ReportExportTaskPO entity = new ReportExportTaskPO();
                    String taskId = PrimaryKeyGenerator.generateStringKey();
                    entity.setTaskId(taskId);
                    entity.setSchoolGroupId(generateParameter.getSchoolGroupId());
                    entity.setSectionCode(generateParameter.getSection());
                    entity.setSchoolGuid(generateParameter.getSchoolGuid());
                    entity.setSchoolName(generateParameter.getSchoolName());
                    entity.setCodeType(generateParameter.getCodeType());
                    entity.setDateCode(generateParameter.getDateCode());
                    entity.setState(1);
                    entity.setContent("处理中");
                    reportExportTaskMapper.insert(entity);
                    return ReportResult.builder()
                            .taskId(taskId)
                            .state(1)
                            .url("处理中")
                            .build();
                });
    }

    @Override
    public void finish(String taskId, ReportResult result) {
        if (result.isDebug()) {
            return;
        }
        reportExportTaskMapper.update(null, Wrappers.<ReportExportTaskPO>lambdaUpdate()
                .set(ReportExportTaskPO::getState, 2)
                .set(ReportExportTaskPO::getUpdateTime, System.currentTimeMillis())
                .set(ReportExportTaskPO::getContent, result.getUrl())
                .eq(ReportExportTaskPO::getTaskId, taskId)
        );
    }

    @Override
    public void failure(String taskId, Throwable throwable) {
        reportExportTaskMapper.update(null, Wrappers.<ReportExportTaskPO>lambdaUpdate()
                .set(ReportExportTaskPO::getState, -1)
                .set(ReportExportTaskPO::getUpdateTime, System.currentTimeMillis())
                .set(ReportExportTaskPO::getContent, throwable.getMessage())
                .eq(ReportExportTaskPO::getTaskId, taskId)
        );
    }

    @Override
    public ReportResult get(String taskId) {
        ReportExportTaskPO po = reportExportTaskMapper.selectOne(Wrappers.<ReportExportTaskPO>lambdaQuery()
                                                                         .eq(ReportExportTaskPO::getTaskId, taskId));
        if (Objects.isNull(po)) {
            throw new ServiceException("任务不存在");
        }
        return ReportResult.builder()
                .taskId(po.getTaskId())
                .state(po.getState())
                .url(po.getContent())
                .build();
    }

    @Override
    public SchoolReportFileData getReportForCompress(ReportExportParameter parameter) {

        HistoryReportFromUpgradePO historyReportFromUpgradePO = historyReportFromUpgradeMapper.selectOne(Wrappers.<HistoryReportFromUpgradePO>lambdaQuery()
                                                                                                                 .eq(HistoryReportFromUpgradePO::getSchoolGroupId, parameter.getSchoolGroupId().toString())
                                                                                                                 .eq(HistoryReportFromUpgradePO::getSchoolGuid, parameter.getSchoolGuid())
                                                                                                                 .eq(HistoryReportFromUpgradePO::getCodeType, parameter.getCodeType())
                                                                                                                 .eq(HistoryReportFromUpgradePO::getDateCode, parameter.getDateCode())
        );

        ReportExportTaskPO reportExportTaskPO = reportExportTaskMapper.selectOne(Wrappers.<ReportExportTaskPO>lambdaQuery()
                                                                                         .eq(ReportExportTaskPO::getSchoolGroupId, parameter.getSchoolGroupId())
                                                                                         .eq(ReportExportTaskPO::getSchoolGuid, parameter.getSchoolGuid())
                                                                                         .eq(ReportExportTaskPO::getSectionCode, parameter.getSection())
                                                                                         .eq(ReportExportTaskPO::getState, 2)
                                                                                         .eq(ReportExportTaskPO::getCodeType, parameter.getCodeType())
                                                                                         .eq(ReportExportTaskPO::getDateCode, parameter.getDateCode())
        );

        //        生生课堂校长月报文件名称：四川省凉山州西昌第一中学（202403）生生课堂应用月度简报
        //        资源平台校长月报文件名称：四川省凉山州西昌第一中学（202403）应用月度简报（高中）
        //        打包文件名称：四川省凉山州西昌第一中学（202403）应用月度简报
        SchoolReportFileData.SchoolReportFileDataBuilder builder = SchoolReportFileData.builder();
        List<DocFileData> docFileDataList = new ArrayList<>();
        String zipFileName = "";

        if (!Objects.isNull(historyReportFromUpgradePO)) {
            zipFileName = new StringBuilder()
                    .append(historyReportFromUpgradePO.getSchoolName())
                    .append("(")
                    .append(historyReportFromUpgradePO.getDateCode())
                    .append(")")
                    .append("应用月度简报").toString();

            String docFileName = new StringBuilder()
                    .append(historyReportFromUpgradePO.getSchoolName())
                    .append("(")
                    .append(historyReportFromUpgradePO.getDateCode())
                    .append(")")
                    .append("生生课堂应用月度简报").toString();
            DocFileData shoolFileData = DocFileData.builder().docFileName(docFileName).url(historyReportFromUpgradePO.getUrl()).build();
            docFileDataList.add(shoolFileData);
        }
        if (!Objects.isNull(reportExportTaskPO)) {
            zipFileName = new StringBuilder()
                    .append(reportExportTaskPO.getSchoolName())
                    .append("(")
                    .append(reportExportTaskPO.getDateCode())
                    .append(")")
                    .append("应用月度简报").toString();
            String docFileName = new StringBuilder()
                    .append(reportExportTaskPO.getSchoolName())
                    .append("(")
                    .append(reportExportTaskPO.getDateCode())
                    .append(")")
                    .append("应用月度简报(")
                    .append(Section.getByCode(reportExportTaskPO.getSectionCode()).getName())
                    .append(")").toString();
            DocFileData schoolFileData = DocFileData.builder().docFileName(docFileName).url(reportExportTaskPO.getContent()).build();
            docFileDataList.add(schoolFileData);
        }

        return builder.zipFileName(zipFileName).docFileData(docFileDataList).build();
    }
}
